home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_04 / allison / convert4.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-06  |  778 b   |  67 lines

  1. LISTING 4 - Shows that only one user-defined conversion is
  2. allowed
  3.  
  4. // convert4.cpp
  5. #include <iostream.h>
  6.  
  7. struct B;
  8.  
  9. struct A
  10. {
  11.     double x;
  12.  
  13.     A(const B& b);
  14. };
  15.  
  16. void f(const A& a)
  17. {
  18.     cout << "f: " << a.x << endl;
  19. }
  20.  
  21. struct B
  22. {
  23.     double y;
  24.  
  25.     B(double d) : y(d)
  26.     {
  27.         cout << "B::B(double)" << endl;
  28.     }
  29. };
  30.  
  31. A::A(const B& b) : x(b.y)
  32. {
  33.     cout << "A::A(const B&)" << endl;
  34. }
  35.  
  36. main()
  37. {
  38.     A a(1);
  39.     f(a);
  40.  
  41.     B b(2);
  42.     f(b);
  43.  
  44.     // The following won't compile:
  45. //  f(3);
  46.  
  47.     // But these will:
  48.     f(B(3));
  49.     f(A(4));
  50.     return 0;
  51. }
  52.  
  53. // Output:
  54. B::B(double)
  55. A::A(const B&)
  56. f: 1
  57. B::B(double)
  58. A::A(const B&)
  59. f: 2
  60. B::B(double)
  61. A::A(const B&)
  62. f: 3
  63. B::B(double)
  64. A::A(const B&)
  65. f: 4
  66.  
  67.